package com.substation.ui.activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.annotation.IdRes;
import android.widget.RadioGroup;

import com.substation.R;
import com.substation.ui.fragment.HomeFragment;
import com.substation.ui.fragment.KnowledgeFragment;
import com.substation.ui.fragment.MyFragment;

import butterknife.BindView;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    int select = 0;
    Fragment homeFragment, knowledgeFragment, myFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        selecte(select);
        radioGroup.check(R.id.home);
        radioGroup.setOnCheckedChangeListener(this);
    }

    /**
     * 设置fragment显示以及切换
     *
     * @param i
     */
    private void selecte(int i) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction, i);
        switch (i) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    fragmentTransaction.add(R.id.content, homeFragment);
                } else {
                    fragmentTransaction.show(homeFragment);
                }
                break;
            case 1:
                if (knowledgeFragment == null) {
                    knowledgeFragment = new KnowledgeFragment();
                    fragmentTransaction.add(R.id.content, knowledgeFragment);
                } else {
                    fragmentTransaction.show(knowledgeFragment);
                }
                break;
            case 2:
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    fragmentTransaction.add(R.id.content, myFragment);
                } else {
                    fragmentTransaction.show(myFragment);
                }
                break;
        }
        fragmentTransaction.commit();
    }


    private void hideFragment(FragmentTransaction ft, int i) {
        if (homeFragment != null && i != 0)
            ft.hide(homeFragment);
        if (knowledgeFragment != null && i != 1)
            ft.hide(knowledgeFragment);
        if (myFragment != null && i != 2)
            ft.hide(myFragment);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.home:
                select = 0;
                break;
            case R.id.knowledge:
                select = 1;
                break;
            case R.id.my:
                select = 2;
                break;
        }
        selecte(select);
    }
}
